import sys
import json
from PySide6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QFileDialog, QMessageBox
import config


class ConfigGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.load_config()

    def init_ui(self):
        # 创建文本框和标签
        self.pattern_label = QLabel("<b>PATTERN</b> (in Regular Expression)")
        self.pattern_input = QLineEdit()
        self.suffix_label = QLabel("<b>SUFFIX</b> (like .log, .txt, etc.)")
        self.suffix_input = QLineEdit()
        self.encoding_label = QLabel(
            "<b>ENCODING</b> (like utf-8, gbk, windows-1252, etc.)")
        self.encoding_input = QLineEdit()

        # 创建功能按钮
        self.extract_from_all_files = QPushButton("Extract From All Files")
        self.extract_from_one_file = QPushButton("Extract From One File")

        # 将按钮的点击事件连接到相应的槽函数
        self.extract_from_all_files.clicked.connect(
            self.extract_data_from_all_files)
        self.extract_from_one_file.clicked.connect(
            self.extract_data_from_one_file)

        # 创建垂直布局
        VL_1 = QVBoxLayout()
        VL_1.addWidget(self.pattern_label)
        VL_1.addWidget(self.pattern_input)
        VL_1.addWidget(self.suffix_label)
        VL_1.addWidget(self.suffix_input)
        VL_1.addWidget(self.encoding_label)
        VL_1.addWidget(self.encoding_input)

        # 创建水平布局
        HL_1 = QHBoxLayout()

        HL_1.addWidget(self.extract_from_all_files)
        HL_1.addWidget(self.extract_from_one_file)

        # 将水平布局添加到垂直布局中
        VL_1.addLayout(HL_1)

        # 设置布局
        self.setLayout(VL_1)

        # 将文本框的文本修改事件连接到保存配置的槽函数
        self.pattern_input.textChanged.connect(self.save_config)
        self.suffix_input.textChanged.connect(self.save_config)
        self.encoding_input.textChanged.connect(self.save_config)

        # 设置窗口固定大小
        self.setFixedSize(400, 200)

    def load_config(self):
        config_data = config.read_config()
        self.pattern_input.setText(config_data["pattern"])
        self.suffix_input.setText(config_data["suffix"])
        self.encoding_input.setText(config_data["encoding"])

    def save_config(self):
        config_data = {
            "pattern": self.pattern_input.text(),
            "suffix": self.suffix_input.text(),
            "encoding": self.encoding_input.text()
        }
        config.save_config(config_data)

    def extract_data_from_all_files(self):
        selected_path = QFileDialog.getExistingDirectory(self, "选择日志文件路径", ".")

        # 在这里实现数据提取的功能
        pattern = self.pattern_input.text()
        suffix = self.suffix_input.text()
        encoding = self.encoding_input.text()

        # 在这里实现数据提取的功能
        import extract_data_from_log
        ret = extract_data_from_log.extract_data(
            self.selected_path, suffix, pattern, encoding)
        if ret == -1:
            QMessageBox.warning(self, "Warning", "未找到任何日志文件。")
        else:
            QMessageBox.information(
                self, "Information", "提取到有效数据 {} 条。".format(ret))

    def extract_data_from_one_file(self):
        selected_file, _ = QFileDialog.getOpenFileName(
            self, "选择日志文件", ".", "日志文件 (*.log *.txt)")

        # 在这里实现数据提取的功能
        pattern = self.pattern_input.text()
        encoding = self.encoding_input.text()

        # 在这里实现数据提取的功能
        try:
            with open(selected_file, encoding=encoding) as f:
                data = f.read()

            import re
            match = re.findall(pattern, data)

            if not match:
                QMessageBox.warning(self, "Warning", "未找到任何匹配项！")
                return
            else:
                # print(match)
                original_path = selected_file[:selected_file.rfind('/')+1]
                print(f"original_path: {original_path}")
                ret = self.save_to_csv(original_path, match)
                if ret == 0:
                    QMessageBox.information(
                        self, "Information", "提取到有效数据 {} 条。".format(len(match)))
                else:
                    QMessageBox.warning(self, "Warning", "保存数据到 csv 文件失败！")

        except UnicodeDecodeError:
            QMessageBox.warning(self, "Warning", "文件解码失败！")
        except FileNotFoundError:
            QMessageBox.warning(self, "Warning", "未选择文件！")

    def save_to_csv(self, original_path, match):

        csv_file = original_path + "extracted_data_of_one_file.csv"
        print(f"csv_file: {csv_file}")
        try:
            with open(csv_file, mode='w', newline='') as file:

                import csv
                writer = csv.writer(file)
                for value in match:
                    writer.writerow([value])

            return 0
        except Exception as e:
            return 1


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ConfigGUI()
    window.setWindowTitle("Extract Data From Log")
    window.show()
    sys.exit(app.exec())
